import tkinter as tk
from typing import Tuple

from win32api import GetSystemMetrics

_screen_wh = GetSystemMetrics(0), GetSystemMetrics(1)


def ix2px(i: int):
    """
    分辨率无关尺寸转换实现，x轴
    :param i: 正数，百分比的数字
    :return: 适应了分辨率的数字
    """
    return int(_screen_wh[0] / 100 * i)


def iy2px(i: int):
    """
    分辨率无关尺寸转换实现，y轴
    :param i: 正数，百分比的数字
    :return: 适应了分辨率的数字
    """
    return int(_screen_wh[1] / 100 * i)


def init_root(root: tk.Tk,
              width: int | float,
              height: int | float,
              title: str | None = None,
              is_x_resizable: bool = True,
              is_y_resizable: bool = True,
              is_no_title_bar: bool = False,
              is_top_most: bool = False,
              bg: str | None = None,
              is_transparent: bool = False,
              icon: str | None = None, x=None, y=None, **kwargs) -> Tuple[int, int, tk.Frame]:
    """
    窗口初始化
    :param root: 窗口实例
    :param title: 窗口标题
    :param width: 窗口宽度或相对0~1
    :param height: 窗口高度或相对0~1
    :param is_x_resizable: 是否可调整横向大小
    :param is_y_resizable: 是否可调整纵向大小
    :param is_no_title_bar: 是否不显示标题栏
    :param is_top_most: 是否始终置顶
    :param bg: 窗口背景
    :param is_transparent: 窗口是否透明
    :param icon 窗口图标路径

    :return 窗口宽高，因为相对宽高需要知道方便接下来布局
    """
    # 无边框
    root.overrideredirect(is_no_title_bar)
    # 初始化容器部件
    root.grid_columnconfigure(0, weight=1)
    root.grid_rowconfigure(0, weight=1)
    ret: tk.Frame
    # 标题
    if title is not None:
        root.title(title)
    # 是否可以调整大小
    root.resizable(is_x_resizable, is_y_resizable)
    # 置顶
    root.wm_attributes('-topmost', 'true' if is_top_most else 'false')
    # 背景
    if bg is not None:
        root.config(bg=bg)
        if is_transparent:
            root.wm_attributes('-transparentcolor', bg)
    # hwnd = windll.user32.GetParent(root.winfo_id())
    # style = windll.user32.GetWindowLongPtrW(hwnd, -20)
    # style = style & ~ 0x00000080
    # style = style | 0x00040000
    # res = windll.user32.SetWindowLongPtrW(hwnd, -20, style)
    # root.wm_withdraw()
    # root.after(0, lambda: root.wm_deiconify())
    # 窗口ico图标设置
    if icon is not None:
        if isinstance(root, tk.Tk):
            root.iconbitmap(icon, icon)
        else:
            root.iconbitmap(icon)
    # 窗口大小和位置,没大小就无法设置位置,仅支持位置居中
    ret = tk.Frame(root)
    ret.grid(row=0, column=0, sticky=tk.NSEW)
    if width != 0 or height != 0:
        sw = root.winfo_screenwidth()
        sh = root.winfo_screenheight()
        if type(width) is float:
            width = int(sw * width)
        if type(height) is float:
            height = int(sh * height)
        if x is None:
            x = (sw / 2) - (width / 2)
        if y is None:
            y = (sh / 2) - (height / 2)
        s = '%dx%d+%d+%d' % (width, height, x, y)
        root.geometry(s)
    # 返回宽高和容器
    return width, height, ret


def override_window_close(window: tk.Tk, fun):
    """
    重写点击关闭按钮的回调函数
    :param window: 窗口实例
    :param fun: 回调函数
    """
    window.protocol('WM_DELETE_WINDOW', fun)

# def tk_image(path: str):
#     """
#     tkinter图片适配,返回的图片对象需要用变量持有避免回收显示为空白
#     :param path: 图片路径
#     :return: 原图，图片对象
#     """
#     ori = Image.open(path)
#     img = ImageTk.PhotoImage(ori)
#     return ori, img
#
#
# def set_opencv_image_to_tk(label, img, img_size=None):
#     img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#     img = Image.fromarray(img)
#     if img_size is not None:
#         img = img.resize(img_size)
#     # img = img[:, :, ::-1]
#     imgtk = ImageTk.PhotoImage(image=img, master=label)
#     label.imgtk = imgtk
#     label.config(image=imgtk)
#
#
# def show_custom_view(parent, message=None, view=None, x=0, y=0):
#     """自定义界面显示"""
#     l = None
#     if message is not None:
#         l = tk.Label(parent, text=message, relief='ridge', anchor=tk.NW, justify=tk.LEFT)
#         l.place(x=x, y=y)
#     elif view is not None:
#         l = view
#         l.place(x=x, y=y)
#     else:
#         print('需要传入显示的内容')
#         return
#
#     def focus_lose_close(e):
#         l.destroy()
#
#     l.bind("<FocusOut>", focus_lose_close)
#     l.focus_set()
